package com.springboot.jdk.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * ScheduledThreadPool 案例
 *
 * @author: zr
 * @date: 2021-10-15
 */
public class ScheduledThreadPoolDemo {

    public static void main(String[] args) {
        // 线程池管理器
        ExecutorService executorService = Executors.newScheduledThreadPool(10);
        // 延迟5秒钟，执行任务
        ((ScheduledExecutorService) executorService).schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + ":" + "延迟5秒钟，执行任务");
            }
        }, 5, TimeUnit.SECONDS);

        // 延迟5秒钟，每隔3秒钟执行一次
        ((ScheduledExecutorService) executorService).scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + ":" + "第一种方式：延迟5秒钟，每隔3秒钟，执行任务");
            }
        }, 5, 3, TimeUnit.SECONDS);

        // 延迟5秒钟，每隔3秒钟执行一次
        ((ScheduledExecutorService) executorService).scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + ":" + "第二种方式：延迟5秒钟，每隔3秒钟，执行任务");
            }
        }, 5, 3, TimeUnit.SECONDS);
    }
}
